<template>
  <div class="container">
    <h1>电影排名查询</h1>
    <form @submit.prevent="fetchMovieData">
      <div class="form-group">
        <label for="rank">输入排名:</label>
        <input
          type="number"
          class="form-control"
          id="rank"
          v-model="rank"
          required
        />
      </div>
      <button type="submit" class="btn btn-primary">查询</button>
    </form>

    <div v-if="movie" class="mt-4">
      <h2>{{ movie.MOVIE_NAME }}</h2>
      <p><strong>排名:</strong> {{ rank }}</p>
    </div>

    <div v-if="message" class="mt-4 alert" :class="messageClass">
      {{ message }}
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      rank: '',
      movie: null,
      message: '',
      messageClass: '',
    };
  },
  methods: {
    async fetchMovieData() {
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/rank', {
          params: {
            n: this.rank,
          },
        });

        if (response.data.code === 0) {
          if (response.data.data.length > 0) {
            this.movie = response.data.data[0];
            this.message = '';
          } else {
            this.movie = null;
            this.message = '未找到该排名的电影。';
            this.messageClass = 'alert-warning';
          }
        } else {
          this.movie = null;
          this.message = response.data.msg || '获取电影数据失败，请稍后重试。';
          this.messageClass = 'alert-danger';
        }
      } catch (err) {
        this.movie = null;
        this.message = '请求失败，请检查网络连接或稍后重试。';
        this.messageClass = 'alert-danger';
      }
    },
  },
};
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-control {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  padding: 10px 15px;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

.btn-primary {
  background-color: #007bff;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background-color: #0056b3;
  transform: scale(1.05);
}

.alert {
  border-radius: 8px;
  padding: 10px 15px;
  margin-top: 20px;
  animation: slideIn 0.5s ease-in-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

.alert-warning {
  background-color: #fff3cd;
  color: #856404;
}

.alert-danger {
  background-color: #f8d7da;
  color: #721c24;
}
</style>